<template>
  <el-dialog
    :title="isEdit ? '编辑物业公司' : '新增物业公司'"
    :visible="visible"
    width="800px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      v-loading="loading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="公司名称" prop="companyName">
            <el-input
              v-model="form.companyName"
              placeholder="请输入公司名称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司编码" prop="companyCode">
            <el-input
              v-model="form.companyCode"
              placeholder="请输入公司编码"
              maxlength="50"
              :disabled="isEdit"
              @blur="handleCompanyCodeBlur"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="营业执照号" prop="businessLicense">
            <el-input
              v-model="form.businessLicense"
              placeholder="请输入营业执照号"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法定代表人" prop="legalRepresentative">
            <el-input
              v-model="form.legalRepresentative"
              placeholder="请输入法定代表人"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input
              v-model="form.contactPerson"
              placeholder="请输入联系人"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input
              v-model="form.contactPhone"
              placeholder="请输入联系电话"
              maxlength="20"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系邮箱" prop="contactEmail">
            <el-input
              v-model="form.contactEmail"
              placeholder="请输入联系邮箱"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="成立日期" prop="establishedDate">
            <el-date-picker
              v-model="form.establishedDate"
              type="date"
              placeholder="请选择成立日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="注册资本(万元)" prop="registeredCapital">
            <el-input-number
              v-model="form.registeredCapital"
              placeholder="请输入注册资本"
              :min="0"
              :precision="2"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资质等级" prop="qualificationLevel">
            <el-select
              v-model="form.qualificationLevel"
              placeholder="请选择资质等级"
              style="width: 100%"
            >
              <el-option label="一级" value="一级" />
              <el-option label="二级" value="二级" />
              <el-option label="三级" value="三级" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="服务范围" prop="serviceScope">
        <el-input
          v-model="form.serviceScope"
          type="textarea"
          placeholder="请输入服务范围"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="公司地址" prop="address">
        <el-input
          v-model="form.address"
          type="textarea"
          placeholder="请输入公司地址"
          :rows="2"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="收款账户" prop="paymentAccount">
            <el-input
              v-model="form.paymentAccount"
              placeholder="请输入收款账户"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户银行" prop="paymentBank">
            <el-input
              v-model="form.paymentBank"
              placeholder="请输入开户银行"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="微信支付商户号" prop="wechatPayMerchantId">
            <el-input
              v-model="form.wechatPayMerchantId"
              placeholder="请输入微信支付商户号"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付宝商户号" prop="alipayMerchantId">
            <el-input
              v-model="form.alipayMerchantId"
              placeholder="请输入支付宝商户号"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="服务热线" prop="serviceHotline">
            <el-input
              v-model="form.serviceHotline"
              placeholder="请输入服务热线"
              maxlength="20"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="营业时间" prop="businessHours">
            <el-input
              v-model="form.businessHours"
              placeholder="请输入营业时间"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="公司简介" prop="introduction">
        <el-input
          v-model="form.introduction"
          type="textarea"
          placeholder="请输入公司简介"
          :rows="4"
          maxlength="1000"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="收款二维码" prop="paymentQrCode">
        <el-upload
          class="upload-demo"
          action="/api/upload"
          :show-file-list="false"
          :on-success="handleQrCodeSuccess"
          :before-upload="beforeQrCodeUpload"
          :limit="1"
        >
          <el-button type="primary">上传二维码</el-button>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件，且不超过2MB，只能上传一个文件
            </div>
          </template>
        </el-upload>
        <div v-if="form.paymentQrCode" class="qr-code-preview">
          <img :src="form.paymentQrCode" alt="收款二维码" style="width: 100px; height: 100px;" />
        </div>
      </el-form-item>

      <el-form-item label="公司Logo" prop="companyLogo">
        <el-upload
          class="upload-demo"
          action="/api/upload"
          :show-file-list="false"
          :on-success="handleLogoSuccess"
          :before-upload="beforeLogoUpload"
          :limit="1"
        >
          <el-button type="primary">上传Logo</el-button>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件，且不超过2MB，只能上传一个文件
            </div>
          </template>
        </el-upload>
        <div v-if="form.companyLogo" class="logo-preview">
          <img :src="form.companyLogo" alt="公司Logo" style="width: 80px; height: 80px;" />
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '确定' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
/**
 * 物业公司新增/编辑表单组件
 * @author Wu.Liang
 * @date 2025-01-29
 */

import { ref, reactive, watch, nextTick } from 'vue'
import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
import propertyCompanyApi from '@/api/property/propertyCompany'
import type { PropertyCompanyFormData } from '../types/property'
import { showSuccess, showError } from '@/utils/message'

// Props
interface Props {
  visible: boolean
  formData: Partial<PropertyCompanyFormData>
  isEdit: boolean
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  formData: () => ({}),
  isEdit: false
})

// Emits
const emit = defineEmits<{
  success: []
  cancel: []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const loading = ref(false)
const submitLoading = ref(false)

// 表单数据
const form = reactive<PropertyCompanyFormData>({
  companyName: '',
  companyCode: '',
  businessLicense: '',
  legalRepresentative: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  address: '',
  establishedDate: '',
  registeredCapital: undefined,
  serviceScope: '',
  qualificationLevel: '',
  paymentQrCode: '',
  paymentAccount: '',
  paymentBank: '',
  paymentLink: '',
  wechatPayMerchantId: '',
  alipayMerchantId: '',
  companyLogo: '',
  introduction: '',
  businessHours: '',
  serviceHotline: ''
})

// 表单验证规则
const rules: FormRules = {
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { max: 100, message: '公司名称长度不能超过100个字符', trigger: 'blur' }
  ],
  companyCode: [
    { required: true, message: '请输入公司编码', trigger: 'blur' },
    { max: 50, message: '公司编码长度不能超过50个字符', trigger: 'blur' },
    { pattern: /^[A-Z0-9]+$/, message: '公司编码只能包含大写字母和数字', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' },
    { max: 50, message: '联系人姓名长度不能超过50个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactEmail: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  businessLicense: [
    { max: 50, message: '营业执照号长度不能超过50个字符', trigger: 'blur' }
  ],
  legalRepresentative: [
    { max: 50, message: '法定代表人姓名长度不能超过50个字符', trigger: 'blur' }
  ],
  address: [
    { max: 200, message: '公司地址长度不能超过200个字符', trigger: 'blur' }
  ],
  serviceScope: [
    { max: 500, message: '服务范围长度不能超过500个字符', trigger: 'blur' }
  ],
  introduction: [
    { max: 1000, message: '公司简介长度不能超过1000个字符', trigger: 'blur' }
  ],
  serviceHotline: [
    { pattern: /^(1[3-9]\d{9}|0\d{2,3}-?\d{7,8}|400-?\d{3}-?\d{4}|800-?\d{3}-?\d{4})$/, message: '服务热线格式不正确，支持手机号或常见热线号格式', trigger: 'blur' }
  ]
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    companyName: '',
    companyCode: '',
    businessLicense: '',
    legalRepresentative: '',
    contactPerson: '',
    contactPhone: '',
    contactEmail: '',
    address: '',
    establishedDate: '',
    registeredCapital: undefined,
    serviceScope: '',
    qualificationLevel: '',
    paymentQrCode: '',
    paymentAccount: '',
    paymentBank: '',
    paymentLink: '',
    wechatPayMerchantId: '',
    alipayMerchantId: '',
    companyLogo: '',
    introduction: '',
    businessHours: '',
    serviceHotline: ''
  })
}

// 监听表单数据变化
watch(() => props.formData, (newData) => {
  if (newData) {
    Object.assign(form, newData)
    // 延迟清除验证错误，确保数据完全加载后再清除
    nextTick(() => {
      setTimeout(() => {
        formRef.value?.clearValidate()
      }, 100)
    })
  } else {
    resetForm()
  }
}, { immediate: true })

// 监听对话框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      nextTick(() => {
        formRef.value?.clearValidate()
      })
    }
  }
)

// 公司编码失焦校验
const handleCompanyCodeBlur = async () => {
  if (!form.companyCode || props.isEdit) return
  
  try {
    const response = await propertyCompanyApi.checkCompanyCodeExists(form.companyCode)
    if (response.code === 200 && response.data) {
      showError('公司编码已存在，请重新输入')
      form.companyCode = ''
    }
  } catch (error) {
    console.error('检查公司编码失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    let response
    if (props.isEdit) {
      // 编辑模式：直接调用更新接口
      response = await propertyCompanyApi.updatePropertyCompany(props.formData.id!, form)
      
      if (response.code === 200) {
        showSuccess('更新成功')
        emit('success')
      } else {
        showError(response.message || '更新失败')
      }
    } else {
      // 新增模式：先调用注册接口，再调用审核接口
      console.log('开始新增物业公司流程...')
      
      // 第一步：调用注册接口
      console.log('第一步：调用注册接口')
      const registerResponse = await propertyCompanyApi.registerPropertyCompany(form)
      
      if (registerResponse.code !== 200) {
        showError(registerResponse.message || '注册失败')
        return
      }
      
      console.log('注册成功，开始获取物业公司ID...')
      
      // 第二步：根据公司编码获取物业公司ID
      const companyResponse = await propertyCompanyApi.getByCompanyCode(form.companyCode)
      
      if (companyResponse.code !== 200 || !companyResponse.data) {
        showError('获取物业公司信息失败')
        return
      }
      
      const companyId = companyResponse.data.id
      console.log('获取到物业公司ID:', companyId)
      
      // 第三步：调用审核接口，自动审核通过
      console.log('第三步：调用审核接口，自动审核通过')
      const auditData = {
        auditStatus: 1, // 审核通过
        auditRemark: '后台超级管理员自动审核通过'
      }
      
      const auditResponse = await propertyCompanyApi.auditPropertyCompany(companyId, auditData)
      
      if (auditResponse.code === 200) {
        showSuccess('新增成功')
        emit('success')
      } else {
        showError(auditResponse.message || '审核失败')
      }
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    showError('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  emit('cancel')
}

// 文件上传相关
const handleQrCodeSuccess = (response: any) => {
  if (response.code === 200) {
    form.paymentQrCode = response.data
    ElMessage.success('二维码上传成功')
  } else {
    ElMessage.error('二维码上传失败')
  }
}

const handleLogoSuccess = (response: any) => {
  if (response.code === 200) {
    form.companyLogo = response.data
    ElMessage.success('Logo上传成功')
  } else {
    ElMessage.error('Logo上传失败')
  }
}

const beforeQrCodeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

const beforeLogoUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.qr-code-preview,
.logo-preview {
  margin-top: 10px;
  
  img {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
}

.upload-demo {
  .el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
  }
}
</style> 